﻿using JZElectrick.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JZElectrick {
    public partial class LoginForm : Form {
        public LoginForm() {
            InitializeComponent();
        }

        EBService eb;
        bool bg = false;


        public LoginForm(bool bg) {
            InitializeComponent();
            this.bg = bg;
        }

        private void LoginForm_Load(object sender, EventArgs e) {
            //if (bg) {
            //    BeginInvoke(new Action(() => {
            //        Hide();
            //        Opacity = 1;
            //        ShowIcon = true;
            //    }));
            //} else {
            //    Opacity = 1;
            //    ShowIcon = true;
            //}

            BeginInvoke(new Action(() => {
                Hide();
                Opacity = 1;
                ShowIcon = true;
            }));

            eb = new EBService(bg);
            eb.ShowLoginEvent += ShowLogin;
            eb.LoginFailedEvent += LoginFailed;
            eb.LoginSuccessEvent += LoginSuccess;
            eb.ShowDormEvent += ShowDormSelect;
            eb.FinishLoadBalanceEvent += FinishLoadBalance;
            eb.NoNeedForBGRunEvent += MainFormClosed;
            eb.Start();
        }

        void ShowLogin(string username, string psw, string code, Image codeImg) {
            BeginInvoke((Action)delegate () {
                
                if (username != null && username != "" &&
                    psw != null && psw != "" &&
                    code != null && code != "" &&
                    Settings.Default.AutoLogin) {
                    ((Action)delegate () {
                        eb.DoLogin(username, psw, code);
                    }).BeginInvoke(null, null);
                    
                } else {
                    Show();
                }

                if (username != null && username != "") {
                    unameText.Text = username;
                    unameText.ForeColor = Color.Black;
                    if (psw != null && psw != "") {
                        pswText.Text = psw;
                        pswText.ForeColor = Color.Black;
                        pswText.PasswordChar = '·';
                        if (code == null || code == "") {
                            verifyText.Focus();
                            msgLabel.Text = "输入验证码以继续";
                        }
                    } else {
                        pswText.Focus();
                    }
                } else {
                    unameText.Focus();
                }
                
                if (code != null) {
                    verifyText.Text = code;
                    verifyText.ForeColor = Color.Black;
                }
                if (codeImg != null) {
                    codeImgBtn.Text = "";
                    codeImgBtn.Image = codeImg;
                } else {
                    codeImgBtn.Text = "刷新验证码";
                }
                SetCodeLoading(false);
            });
            
        }

        private void codeImgBtn_Click(object sender, EventArgs e) {
            SetCodeLoading(true);
            ((Action)delegate () {
                eb.LoadCode();
            }).BeginInvoke(null, null);
        }

        private void DoLogin() {
            if (CheckLogin()) {
                SetLoginState(true);
                ((Action)delegate () {
                    eb.DoLogin(unameText.Text, pswText.Text, verifyText.Text);
                }).BeginInvoke(null, null);
            }
        }

        private bool CheckLogin() {
            
            if (unameText.Text == placeholders[0] || unameText.Text == "") {
                unameText.Focus();
                return false;
            }
            if (pswText.Text == placeholders[1] || pswText.Text == "") {
                pswText.Focus();
                return false;
            }
            if (verifyText.Text == placeholders[2] || verifyText.Text == "") {
                verifyText.Focus();
                return false;
            }
            return true;
        }
        
        

        private void LoginFailed(string msg) {
            BeginInvoke((Action)delegate () {
                Show();
                SetLoginState(false);
                msgLabel.Text = msg;
            });
            
        }

        private void LoginSuccess() {
            BeginInvoke((Action)delegate () {
                Hide();
                ((Action)delegate () {
                    eb.LoadBalance();
                }).BeginInvoke(null, null);
            });
            
        }

        private void LoginRevoke() {
            Show();
            verifyText.Text = placeholders[2];
            SetCodeLoading(true);
            ((Action)delegate () {
                eb.LoadCode();
            }).BeginInvoke(null, null);
        }

        private void ShowDormSelect(string[] list) {
            BeginInvoke((Action)delegate () {
                DormSelectForm dormSelect = new DormSelectForm(list, eb);
                dormSelect.DormSelectFinishEvent += DormSelectFinish;
                dormSelect.Show();
            });
            
        }

        private void DormSelectFinish(bool back) {
            if (back) {
                LoginRevoke();
            } else {
                LoginSuccess();
            }
        }

        private void ShowAskSaveForm() {
            FinishAskForm askForm = new FinishAskForm();
            askForm.SetSaveStateEvent += SaveState;
            askForm.Show();
        }

        private void SaveState(EBServiceSavingType type) {
            eb.SaveState(type);
        }

        private void FinishLoadBalance(string[] balance) {
            BeginInvoke((Action)delegate () {
                if (bg) {
                    if (balance == null) {
                        //LoginRevoke();
                        MsgForm msgForm = new MsgForm("电量读取失败");
                        msgForm.Show();
                    } else {
                        Close();
                    }
                } else {
                    MainForm mainForm = new MainForm(balance, eb);
                    mainForm.MainFormClosedEvent += MainFormClosed;
                    mainForm.Show();
                }

                if (Settings.Default.FirstLaunch) {
                    ShowAskSaveForm();
                }

            });
        }

        private void MainFormClosed() {
            Close();
        }

        #region ui相关

        string[] placeholders = { "用户名", "密码", "验证码" };
        bool[] textInputing = { true, false, false };

        private void loginTextEnter(object sender, EventArgs e) {
            TextBox current = sender as TextBox;
            textInputing[current.TabIndex] = true;
            if (current.Text == placeholders[current.TabIndex]) {
                current.Text = "";
                current.ForeColor = Color.Black;

                if (Equals(current, pswText)) {
                    current.PasswordChar = '·';
                }
            }
            
        }

        private void loginTextLeave(object sender, EventArgs e) {
            TextBox current = sender as TextBox;
            textInputing[current.TabIndex] = false;
            if (current.Text == "") {
                current.Text = placeholders[current.TabIndex];
                current.ForeColor = Color.Gray;

                if (Equals(current, pswText)) {
                    current.PasswordChar = '\0';
                }
            }
        }
        
        private void loginTextChanged(object sender, EventArgs e) {
            TextBox current = sender as TextBox;
            if (textInputing[current.TabIndex]) {
                var reg = new Regex("^[0-9]*$");
                var str = current.Text.Trim();
                var sb = new StringBuilder();
                if (!reg.IsMatch(str)) {
                    for (int i = 0; i < str.Length; i++) {
                        if (reg.IsMatch(str[i].ToString())) {
                            sb.Append(str[i].ToString());
                        }
                    }
                    current.Text = sb.ToString();
                    current.SelectionStart = current.Text.Length;    //定义输入焦点在最后一个字符
                }
            }
            
        }

        private void loginTextKeyPress(object sender, KeyPressEventArgs e) {
            if (e.KeyChar == '\r') {
                DoLogin();
            }
        }

        private void loginBtn_Click(object sender, EventArgs e) {
            DoLogin();
        }

        private void SetCodeLoading(bool state) {
            if (state) {
                codeImgBtn.Image = null;
                verifyText.Text = placeholders[2];
            }
            verifyText.Enabled = !state;
        }

        private void SetLoginState(bool state) {
            unameText.Enabled = !state;
            pswText.Enabled = !state;
            verifyText.Enabled = !state;
            codeImgBtn.Enabled = !state;
            loginBtn.Enabled = !state;
        }

        #endregion

    }
}
